import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';

// Create axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 15000
});

// Request interceptor
service.interceptors.request.use(
    config => {
      // Get stored token
      const token = localStorage.getItem('token');
      // If the token exists, add it to the request header
      if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
      }
      return config;
    },
    error => {
      console.error('Request error:', error);
      return Promise.reject(error);
    }
);

// Response interceptor
service.interceptors.response.use(
    response => {
      const res = response.data;

      // If the response status code is not in the 200 range, it means there is a problem with the request
      if (response.status < 200 || response.status >= 300) {
        ElMessage.error(res.message || 'Request failed');

        // If unauthorized or token expired
        if (response.status === 401 || response.status === 403) {
          handleTokenExpiration();
        }

        return Promise.reject(new Error(res.message || 'Request failed'));
      } else {
        return res;
      }
    },
    error => {
      console.error('Response error:', error);

      // Handle network errors or server errors
      if (error.response) {
        // Server responded with an error
        const status = error.response.status;
        let message = 'Server error';

        switch (status) {
          case 400:
            message = 'Invalid request parameters';
            break;
          case 401:
            message = 'Unauthorized, please log in again';
            handleTokenExpiration();
            break;
          case 403:
            message = 'Forbidden';
            break;
          case 404:
            message = 'Requested resource not found';
            break;
          case 500:
            message = 'Internal server error';
            break;
          default:
            message = `Request error(${status})`;
        }

        ElMessage.error(error.response.data?.message || message);
      } else if (error.request) {
        // The request was sent but no response was received
        ElMessage.error('No response from the server, please check your network connection');
      } else {
        // There is a problem with the request settings
        ElMessage.error('Request configuration error');
      }

      return Promise.reject(error);
    }
);

// Function to handle token expiration
const handleTokenExpiration = () => {
  // Prompt the user to log in again
  ElMessage.error('Login has expired, please log in again');

  // Clear the stored token and user information
  localStorage.removeItem('token');

  // Jump to the login page
  window.location.href = '/login';
};

// Encapsulate the request method
const request = (config: any) => {
  return service(config);
};

export default request;